///物流回访单
public without sharing class LogisticalFeedBackController {

	public String msg {get;private set;}
	public String dataJson {get; private set;}
	public String searchJson {get;  set;}
	public String cofirmJson {get;  set;}

  public Boolean isBatch {get;set;}

	public String isbackcombox {get; private set;}
	public String invoicecombox {get;private set;}
  public String transportmodecombox {get;private set;}
  public String customerSatisfactioncombox {get;private set;}

	public String search_ncid ;
	public String search_sendtime_begin;
	public String search_sendtime_end ;
	public String search_count_limit ;
	public String search_accountname ;
  public String search_type ;
  public String search_carriername ;

  public String search_outdoordate_begin{get;set;} 
  public String search_outdoordate_end{get;set;}

  public String fbRcordId ;


    public LogisticalFeedBackController() {
        setNil();
        fbRcordId = Utils.getRecordTypeIdByDevNameAndObjName('LogicFeedBack', 'Feedback__c');
       isbackcombox =  getOptMap(ImportObject.getPicklistValues('Feedback__c', 'IsBack__c', true));
       invoicecombox =  getOptMap(ImportObject.getPicklistValues('Feedback__c', 'HasBill__c', true));
       transportmodecombox = getOptMap(ImportObject.getPicklistValues('Feedback__c', 'TransportMode__c', true));
       customerSatisfactioncombox = getOptMap(ImportObject.getPicklistValues('Feedback__c', 'CustomerSatisfaction__c', true));
    }
    public void setNil(){
    	msg = '';
    	dataJson = '';
    	searchJson = '';
    	search_ncid = '';
    	search_sendtime_begin = '';
    	search_sendtime_end = '';
    	search_count_limit = '';
    	search_accountname = '';
      search_type = '';
      search_carriername = '';

    }


    public String getOptMap(Map<String,String> opts){
    
      List<Map<String,String>>  dList = new List<Map<String,String>>();
      for (String k : opts.keySet()) {
        Map<String ,String> dataMap = new Map<String,String>();
        dataMap.put('id',opts.get(k) );
        dataMap.put('text',k );
        dList.add(dataMap);
      }  
      
      return EncodingUtil.urlEncode(JSON.serialize(dList), 'UTF-8');
    }



     @RemoteAction
    public static Map<String ,Object> query(String sql   ){

        Map<String,Object> tmp= new Map<String,Object>();
        List<BackBill__c> bList = (List<BackBill__c>) Database.query(sql);
        tmp.put('data',genBBList(bList)) ;
        tmp.put('size', Database.countQuery(sql.replaceFirst('select.*from','select count() from ').replaceFirst('order by.*',' ') ));
        return tmp;

    }

    public static List<BackBillBean> genBBList(List<BackBill__c> bList ){
        Set<String> outdoors = new Set<String>();

        for(BackBill__c b :bList){
          outdoors.add(b.OutgoingNumber__c );
        }
        Map<String ,String > outdoorMap = getComfirmedOutdoors(outdoors);
        outdoors.clear();
        List<BackBillBean> bbLsit = new List<BackBillBean>();
        for(BackBill__c b : bList){
          bbLsit.add(new BackBillBean(b,outdoorMap.get(b.OutgoingNumber__c) != null ));
        }
        return bbLsit;
    }

     @RemoteAction
    public static Map<String ,Object> queryMore(String sql,String tagId  ){

        Map<String,Object> tmp= new Map<String,Object>();
        tmp.put('size', Database.countQuery(sql.replaceFirst('select.*from','select count() from ').replaceFirst('order by.*',' ') ));

        if (tagId != null && tagId.trim().length() >0 )   sql =   sql.replace('order by', ' and Id > \''+tagId+'\'  order by ');// :  sql.replace('order by', ' limit '+batchnum+' order by ');
        System.debug('queryMore==>'+sql);
        List<BackBill__c> bList = (List<BackBill__c>) Database.query(sql);
        tmp.put('data', genBBList(bList)) ;
        return tmp;

    }

    private static  Map<String,String> getComfirmedOutdoors(Set<String> ncids ){

        Map<String,String> outdoors = new Map<String,String>();
        for (FeedBack__c fb  :[select Id ,ExwareNo__c from FeedBack__c where ExwareNo__c in:ncids ] ) {
            outdoors.put(fb.ExwareNo__c, fb.ExwareNo__c );
        }
        return outdoors;

    }


    //获取返单记录
   /* public void getLogicFeedBack(){
       // Date currentD = Date.valueOf(System.now()).toStartOfMonth();
       // Date lastD =  Date.newInstance(System.now().year(), System.now().month(), Date.daysInMonth(System.now().year(), System.now().year()));         

        System.debug(search_outdoordate_begin);
        System.debug(search_outdoordate_end);
        Date startD = search_outdoordate_begin == null || search_outdoordate_begin==''  ? Date.valueOf(System.now()).toStartOfMonth():  Date.valueOf(search_outdoordate_begin);
        Date endD = search_outdoordate_end == null || search_outdoordate_end=='' ? Date.newInstance(System.now().year(), System.now().month(), Date.daysInMonth(System.now().year(), System.now().year())):   Date.valueOf(search_outdoordate_end);


        Map<String,String> outdoors = new Map<String,String>();
        List<BackBill__c> bList = new List<BackBill__c>();
        for (BackBill__c b :[select Id,OutgoingNumber__c,OutdoorDate__c,IsBack__c ,AccountName__c,Remark__c,TransMethod__c,Saler__c
          from BackBill__c where OutdoorDate__c>=:startD and  OutdoorDate__c<=:endD order by OutgoingNumber__c  ] ) {
            outdoors.put(b.OutgoingNumber__c,null );
            bList.add(b);
        }

       
        outdoors = getComfirmedOutdoors(outdoors.keySet());

        List<BackBillBean> tmp = new List<BackBillBean>();

        for (BackBill__c b  : bList) {
            
            tmp.add(new BackBillBean(b,outdoors.get(b.OutgoingNumber__c) != null ));
        }
        outdoors.clear();
        bList.clear();
        dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8') ;

    }*/


    public void search(){
    	
    	Map<String ,Object > condition = (Map<String ,Object> )JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson, 'UTF-8'));
    	System.debug(condition);
    	setNil();
    	String wherestr = ' where  ';
   	   search_ncid =  String.valueOf(condition.get('ncid')) ;
   	   search_sendtime_begin =  String.valueOf(condition.get('sendtime_begin')) ;
   	   search_sendtime_end =  String.valueOf(condition.get('sendtime_end')) ;
   	   search_count_limit =  String.valueOf(condition.get('count_limit')) ;
   	   search_accountname =  String.valueOf(condition.get('accountname')) ;
       search_type =  String.valueOf(condition.get('type')) ;
       search_carriername =  String.valueOf(condition.get('carriername')) ;

   	   if(String.isBlank(search_count_limit) == false){
   	   		wherestr += '  rownum  <=  '+search_count_limit ;
   	   }else{
   	   		wherestr += '  rownum  <=  50  ';
   	   }

   	   if(String.isBlank(search_ncid) == false){
   	   		wherestr += ' and  t.ncid  like \'%'+search_ncid+'%\'  ';
   	   }
   	   if(String.isBlank(search_accountname) == false){
   	   		wherestr += ' and  t.accountname  like \'%'+search_accountname+'%\'  ';
   	   }

      /* System.debug(search_type);
       System.debug(String.isBlank(search_type) == false);
       if(String.isBlank(search_type) == false){
          wherestr += ' and  t.type  = ' +search_type+'  ';
       }

       if(String.isBlank(search_carriername) == false){
          wherestr += ' and  t.CARRIERNAME  like \'%'+search_carriername+'%\'  ';
       }*/

       if(String.isBlank(search_accountname) == false){
          wherestr += ' and  t.accountname  like \'%'+search_accountname+'%\'  ';
       }
   	   if(String.isBlank(search_sendtime_begin) == false){
   	   		wherestr += ' and  t.sendtime  >=  \''+search_sendtime_begin+'\'  ';
   	   }
   	   if(String.isBlank(search_sendtime_end) == false){
   	   		wherestr += ' and  t.sendtime  <=  \''+search_sendtime_end+'\'  ';
   	   }

       wherestr += ' order by ncid ';
   	   
   	   getLogicOrders(getSql() + wherestr );




    }
    @RemoteAction 
    public static String importBackBills(String dataJson){
        Map<String,Object> resultMap = new Map<String,Object>();
        List<Object> cList = (List<Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(dataJson, 'UTF-8'));
        dataJson = '';
        List<BackBill__c> bList = new List<BackBill__c>();
        List<Object> errData = new List<Object>();
        for (Object o : cList) {
              Map<String,Object> mo = (Map<String,Object>) o ; 

              try {
                BackBill__c b = new BackBill__c();
                b.OutdoorDate__c = mo.get('outdate') == null ? null : Date.valueOf(String.valueOf(mo.get('outdate')).trim());
                b.OutgoingNumber__c = mo.get('ncid') == null ? null :  String.valueOf(mo.get('ncid')).trim();
                b.IsBack__c = mo.get('isback') == null ? null :  String.valueOf(mo.get('isback')).trim();
                b.AccountName__c = String.valueOf(mo.get('accountname'));
                b.TransMethod__c = String.valueOf(mo.get('transmethod'));
                b.Remark__c = String.valueOf(mo.get('remark'));
                b.Saler__c = String.valueOf(mo.get('saler'));
                b.CarrierName__c = String.valueOf(mo.get('carriername'));
                bList.add(b);
              }catch (Exception e) {
                  mo.put('msg',e.getMessage() + ' '+e.getStackTraceString());
                  errData.add(mo);
                  continue;

              }
           
          }

          System.debug('importBackBills==>'+errData);
    
        SavePoint sp = Database.setSavepoint();
        try {

          if(bList.size() > 0) upsert bList OutgoingNumber__c;
            resultMap.put('code', '1');
            resultMap.put('msg', 'success');
        }catch (Exception e) {
            Database.rollback(sp);
            for (BackBill__c b  :bList ) {
              Map<String,Object> mo = new Map<String,Object>();
              mo.put('ncid', b.OutgoingNumber__c);
              mo.put('outdate', b.OutdoorDate__c);
              mo.put('isback', b.IsBack__c);
              mo.put('msg', e.getMessage() + ' '+ e.getStackTraceString());
              mo.put('accountname', b.AccountName__c);
              mo.put('transmethod', b.TransMethod__c);
              mo.put('remark', b.Remark__c);
              mo.put('saler', b.Saler__c);
              mo.put('carriername', b.CarrierName__c);
              errData.add(mo);
            }
            resultMap.put('code', '0');
            resultMap.put('msg', 'error');
        }
        resultMap.put('errData',errData);
          System.debug('importBackBills2==>'+errData);
       return EncodingUtil.urlEncode(JSON.serialize(resultMap), 'UTF-8') ;


    }
    public void getLogicOrders(){

    	getLogicOrders(getSql() +' where rownum <= 50  order by ncid ');
    }
    ///获取物流单据
    private void getLogicOrders(String sql ){

    	msg = '';
    	
        String postURL = Label.queryTmsURL;
        System.debug(sql);
        String timestamp = String.valueOf(System.now().getTime());
        String data =EncodingUtil.base64Encode(Blob.valueOf(sql));

        String sign = EncodingUtil.convertToHex(Crypto.generateDigest('MD5',Blob.valueOf(timestamp+data  + timestamp)));
        ///发送请求
        //生成POST请求
        System.debug(data);
        System.debug(timestamp);
         System.debug(sign);
        HttpRequest req = new HttpRequest(); 
        req.setBody('data=' +  EncodingUtil.urlEncode(data,'UTF-8')+'&timestamp='+timestamp+'&sign='+sign);
        req.setEndpoint(postURL); 
        req.setMethod('POST');
        HttpResponse res = Utils.postRequest(req,1); 
             		System.debug(res.getBody());

         if (res.getStatusCode() == 200) {


             Map<String,Object> r =null;
                 //如果是测试
                if(Test.isRunningTest()){
                  Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  resBody.put('result','{"code":"1","msg":"success","data":[{"carriername":"成都通驰物流有限公司","accountname":"绵阳市中心医院","ncid":"JC021808010001","owno":"1005","boxnum":null,"tmsnotes":null,"owname":"迈克实业有限公司","contact":null,"carrymehtod":"通驰","rownum":2,"accountno":"0000025060","sendtime":"2018-08-03 13:38:11","notes":"发货运到绵阳市中心医院，18228054547，李志林","carrierno":"1009804"}]}');
                    r =  resBody;
                }else{
                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                }

             if(r.get('code') == 0|| r.get('code')=='0' ){
             		Map<String, Object> res1 = (Map<String, Object> ) JSON.deserializeUntyped(((String)r.get('result')));
             		if(String.valueOf(res1.get('code')) == '1'){
             			//List<Object> datas = (List<Object> ) res.get('data');
             			dataJson =EncodingUtil.urlEncode(JSON.serialize(res1.get('data')), 'UTF-8')  ;
             		}else{
             			msg = String.valueOf(res1.get('msg'));
             		}
             		System.debug(dataJson);
             		System.debug(msg);

             }else{
             	msg = String.valueOf(r.get('msg'));
             }
         }else{
         	msg = '网络错误!'+ res.getBody();
         }

    }

  
      public void confirmCarrierTotms(){

    	 List<Object> cList = (List<Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(cofirmJson, 'UTF-8'));
		    	if(cList.size() == 0)return ;
		    	String postURL = Label.queryTmsPutURL;
		     	String data = JSON.serialize(cList);
		        String timestamp = String.valueOf(System.now().getTime());
		        String sign = EncodingUtil.convertToHex(Crypto.generateDigest('MD5',Blob.valueOf(timestamp+data + timestamp)));
		        HttpRequest req = new HttpRequest(); 
		        System.debug(data);
		        System.debug(timestamp);
		        System.debug(sign);

		        System.debug(postURL);
		        req.setBody('data=' +data+'&timestamp='+timestamp+'&sign='+sign);
		        req.setEndpoint(postURL); 
		        req.setMethod('POST');
		        HttpResponse res = Utils.postRequest(req,1); 
		           System.debug(res.getBody());

		         if (res.getStatusCode() == 200) {
		         	 Map<String,Object> r =null;
		                 //如果是测试
		                if(Test.isRunningTest()){
		                  Map<String,Object>  resBody= new Map<String,Object>();
		                  resBody.put('code','0');
		                  resBody.put('result','{"code":"1","msg":"success"}');
		                    r =  resBody;
		                }else{
		                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
		                }
		             if(r.get('code') == 0|| r.get('code')=='0' ){
		             		Map<String, Object> res1 = (Map<String, Object> ) JSON.deserializeUntyped(((String)r.get('result')));
		             		if(String.valueOf(res1.get('code')) == '1'){

		             			msg = '确认成功!';
		             		}else{
		             			msg = '确认失败:  '+String.valueOf(res1.get('msg'));
		             		}
		             	}else{
		             		msg = '确认失败:  '+String.valueOf(r.get('msg'));
		             	}
		         }else{
		         	msg = '确认失败:  '+res.getBody();
		         }

    }

    public void confirmCarrier(){
    	msg = '';


       List<Object> eList = (List<Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(cofirmJson, 'UTF-8'));
    		SavePoint sp = Database.setSavepoint();
			
        Set<String> ncidSet = new Set<String>();
       for(Object o : eList){

          Map<String,Object > dataMap  = (Map<String ,Object > ) o;
          ncidSet.add(String.valueOf(dataMap.get('ncid')));
       }
       Map<String , String>ncIdMap = new Map<String,String>();
       for(Feedback__c fb :[select Id ,ExwareNo__c from Feedback__c where ExwareNo__c in: ncidSet and RecordTypeId=:fbRcordId ]){
          ncIdMap.put(fb.ExwareNo__c,fb.Id);

       }
       List<FeedBack__c> fbList = new List<Feedback__c>();
      for(Object o : eList){

          Map<String,Object > dataMap  = (Map<String ,Object > ) o;
           FeedBack__c fb = genFeadBack(dataMap, ncIdMap.get(String.valueOf(dataMap.get('ncid'))) );
           fbList.add(fb);
       }
    	 System.debug(eList);
    	try {
				if(fbList.size() > 0)upsert fbList; 
				
			}catch (Exception e) {
				Database.rollback(sp);
			    msg = '操作失败! ' + e.getMessage();
			    return ;
			}

    }

    private String getSql(){ 	
    	return 'select t.* , rownum  from '+
    	'(select ncid,CARRIERNAME,CUSTOMERID accountno,DEST_CUSTOMER_NAMEC accountname, '+
    	' userdefine1 boxnum, userdefine3 contact, notes ,userdefine2 carrymehtod , userdefine4 tmsnotes ,' +
    	'CARRIERNO, OWNo,OWNAME,to_char(sendtime,\'yyyy-MM-dd HH24:mi:ss\') sendtime '+
    		'from IDX_SO_SF s order by s.SENDTIME   ) t  ' ;

    }

    private Feedback__c  genFeadBack(Map<String,Object> o ,String fbId ){
    	Feedback__c  fb = new Feedback__c();
    	if(fbId != null)fb.Id = fbId ;

    	fb.Name = 'WL-'+String.valueOf(o.get('ncid'));

    	fb.RecordTypeId = fbRcordId;
    	fb.ExwareNo__c = String.valueOf(o.get('ncid'));
    	fb.HasBill__c = String.valueOf(o.get('invoice'));
    	fb.IsBack__c = String.valueOf(o.get('isback'));
    	fb.Callee__c = String.valueOf(o.get('recv'));
    	fb.RecievePerson__c = String.valueOf(o.get('confirmrecv'));
    	fb.ERPComment__c = String.valueOf(o.get('notes'));
    	fb.Comment__c = String.valueOf(o.get('remark'));
    	fb.CarriageNumber__c = String.valueOf(o.get('carrierno'));
    	fb.LogisCompany__c = String.valueOf(o.get('carriername'));
      fb.IsConfirmed__c = true ;
      fb.CustomerSatisfaction__c = String.valueOf(o.get('satisfication')) == '' ? null : String.valueOf(o.get('satisfication')) ;
      try{
        fb.Sendtime__c = DateTime.valueOf(String.valueOf(o.get('sendtime')));
      }catch(Exception e){
        fb.Sendtime__c = null;
      }
      
    	try {
    		fb.RecieveDate__c = Date.valueOf(String.valueOf(o.get('signdate')));
    	}catch (Exception e) {
    	    fb.RecieveDate__c = null;
    	}
    	fb.Client__c = String.valueOf(o.get('accountname'));
    	/*try{
    		System.debug(String.valueOf(o.get('accountno')).right(6) );
    		fb.Client__c = [select Id from Account where AccountNumber =:String.valueOf(o.get('accountno')).right(6) ].Id ;	
    	}catch(Exception e){
    		msg = '在Salesforce中没有匹配到 客户编码为:'+String.valueOf(o.get('accountno')).right(6) +'的客户 ,请联系系统管理员 ';
    		return null;
    	}*/
    	
    	//fb.LogicOnly__c = String.valueOf(o.get('ncid'))+'-'+String.valueOf(o.get('owno'))+'-'+String.valueOf(o.get('carrierno'));
    	return fb;

    }

    public class BackBillBean{
        public String Id ;
        public String ncid ;
        public String isback;
        public String isfeed;
        public String outdate ;
        public String accountname ;
        public String transmethod;
        public String remark ;
        public String saler;
        public String carriername;


        public BackBillBean(BackBill__c b,Boolean isf  ){
          Id = b.Id; 
          ncid = b.OutgoingNumber__c;
          isback = b.IsBack__c;
          outdate =  b.OutdoorDate__c == null ? '':b.OutdoorDate__c.format();
          accountname = b.AccountName__c ; 
          transmethod = b.TransMethod__c;
          remark = b.Remark__c ;
          saler = b.Saler__c ;
          carriername = b.CarrierName__c;
          isfeed = isf ? '是' :'否';
        }
       
    }


}